using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using DataAccessLayer;
using GlobalObjects;
using SharedLIbrary;
using PusherServer;
using System.Globalization;
using System.Threading.Tasks;

namespace FailingSensorMonitoringAgent
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("FailingSensorMonitoringAgent entry point called", "Information");

            while (true)
            {
                try
                {
                    Trace.TraceInformation("Working", "Information");
                    // List<SensorIPDataStructure> failedSensors = new List<SensorIPDataStructure>();
                    PingableSensorList failedSensors = new PingableSensorList();
                    //retrieving the list of sensors with its last accessed time
                    SensorAccessTimeEntity entity = new SensorAccessTimeEntity();
                    List<SensorAccessTime> sensors = entity.getAllSensors_DAL();


                    SensorEntity sensorEntity = new SensorEntity();
                    CultureInfo ukCulture = new CultureInfo("en-GB");

                    //comparing the time with the current utc time
                    DateTime myDate = DateTime.UtcNow;
                    String ukmyDate = myDate.ToString("dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.GetCultureInfo("en-us"));
                    Debug.WriteLine("Current Time:" + ukmyDate);
                    //DateTime now = DateTime.Parse(myDate, System.Globalization.CultureInfo.GetCultureInfo("en-gb"));

                    DateTime now = DateTime.Parse(ukmyDate, ukCulture.DateTimeFormat);
                    Debug.WriteLine("Current Parsed Time:" + now);

                    foreach (var sensor in sensors)
                    {
                        try
                        {
                            if (sensorEntity.getSensorStatus_DAL(sensor.sensorId))
                            {
                                DateTime lastAccess;
                                if (DateTime.TryParse(sensor.lastAccess, out lastAccess))
                                {
                                    if ((now - lastAccess).TotalSeconds > sensor.faultTolerance)
                                    {
                                        sensorEntity.setSensorStatus_DAL(sensor.sensorId, false);
                                        //add the sensor id and device ip address to a pingable sensors list, if it already does not exist
                                        failedSensors.setPingSensor(sensor.sensorId, sensor.ip);
                                        //push an event that sensor has failed.
                                        // Task.Factory.StartNew(() => this.PusherNearestSensor(sensor, sensor.sensorId));

                                        // SensorEntity sensorEntity = new SensorEntity();

                                        List<SensorDistance> allsensors = sensorEntity.getNearestSensors_DAL(sensor.sensorId);
                                        if (allsensors.Count == 0)
                                        {
                                            var pusher = new Pusher("49656", "3a96bb88c88f38d16083", "319cf390152ad39a1132");
                                            var result = pusher.Trigger(sensorEntity.getSensorById_DAL(sensor.sensorId).Deviceid.ToString(), sensor.sensorId.ToString(), new { message = "Sensor Not Working", distance = "0", sensorId = sensor.sensorId });
                                        }
                                        else
                                        {
                                            for (int i = 0; i < allsensors.Count; i++)
                                            {
                                                if (sensorEntity.getSensorStatus_DAL(allsensors[i].sensorId))
                                                {
                                                    var pusher = new Pusher("49656", "3a96bb88c88f38d16083", "319cf390152ad39a1132");
                                                    var result = pusher.Trigger(sensorEntity.getSensorById_DAL(sensor.sensorId).Deviceid.ToString(), sensor.sensorId.ToString(), new { message = "Sensor Not Working", distance = allsensors[i].distance, sensorId = allsensors[i].sensorId });
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {


                        }
                    }
                }
                catch (Exception ex)
                {


                }
                   Thread.Sleep(3000);
            }
        }
        //private void PusherNearestSensor(SensorAccessTime sensor,int sensorId)
        //{
        //    SensorEntity sensorEntity = new SensorEntity();

        //    List<SensorDistance> allsensors = sensorEntity.getNearestSensors_DAL(sensorId);
        //    if (allsensors.Count == 0)
        //    {
        //                var pusher = new Pusher("49656", "3a96bb88c88f38d16083", "319cf390152ad39a1132");
        //                var result = pusher.Trigger(sensorEntity.getSensorById_DAL(sensor.sensorId).Deviceid.ToString(), sensor.sensorId.ToString(), new { message = "Sensor Not Working", distance = "0", sensorId = sensor.sensorId });
        //    }
        //    else
        //    {
        //        for (int i = 0; i < allsensors.Count; i++)
        //        {
        //            if (sensorEntity.getSensorStatus_DAL(allsensors[i].sensorId))
        //            {
        //                           var pusher = new Pusher("49656", "3a96bb88c88f38d16083", "319cf390152ad39a1132");
        //                           var result = pusher.Trigger(sensorEntity.getSensorById_DAL(sensor.sensorId).Deviceid.ToString(), sensor.sensorId.ToString(), new { message = "Sensor Not Working", distance = allsensors[i].distance, sensorId = allsensors[i].sensorId });
        //                break;
        //            }
        //        }
        //    }

        //}
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            return base.OnStart();
        }
    }
}
